package co.edu.uniandes.entregAndes.jms;

import java.util.Hashtable;
import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class QueueProducer {
	private Queue queue;
	private QueueSession queueSession;

	public void inicializar(String queueName) throws JMSException, NamingException {
		Hashtable<String, String> env = new Hashtable<String, String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"org.jnp.interfaces.NamingContextFactory");
		env.put(Context.PROVIDER_URL, "jnp://localhost:1099");
		env.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");

		Context context = new InitialContext(env);

		QueueConnectionFactory queueConectionFactory = (QueueConnectionFactory) context
				.lookup("ConnectionFactory");
		queue = (Queue) context.lookup("queue/"+queueName);
		QueueConnection queueConnection = queueConectionFactory
				.createQueueConnection();
		queueSession = queueConnection.createQueueSession(false,
				QueueSession.SESSION_TRANSACTED);
		queueConnection.start();
		MessageConsumer consumer = queueSession.createConsumer(queue);
		while (consumer.receiveNoWait() != null) {
			System.out.print(".");
		}
	}

	public void sendMessage(String text) throws JMSException {
		QueueSender queueSender = queueSession.createSender(queue);
		TextMessage textMessage = queueSession.createTextMessage(text);
		textMessage.setJMSExpiration(System.currentTimeMillis() + 3000);
		queueSender.send(textMessage);
		queueSender.close();
	}
}
